package com.hna.face.controller.business;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.hna.face.base.BaseController;
import com.hna.face.common.result.BaseResult;
import com.hna.face.model.*;
import com.hna.face.service.IFaceAclsService;
import com.hna.face.service.IFaceSyncInfoService;
import com.hna.face.service.IFaceUsersService;
import com.hna.face.service.IFaceVehicleService;
import com.hna.face.util.App;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


@Controller
public class VehicalController extends BaseController {

	@Autowired 
	IFaceVehicleService facevehicleService;
	@Autowired
	IFaceUsersService userService;
	@Autowired
	IFaceAclsService aclsService;
	@Autowired
	IFaceUsersService usersService;
	@Autowired
    IFaceSyncInfoService faceSyncInfoService;
	
    private final static Logger log = LoggerFactory.getLogger(VehicalController.class);

    @RequestMapping("/vehicle/index")
    public String index() {
        return "pages/vehicle/index";
    }
    
    @RequestMapping("/vehicle/add")
    public String add() {
        return "pages/vehicle/add";
    }
    @RequestMapping("/vehicle/gouser")
    public String gouserList() {
        return "pages/vehicle/child";
    }
    

//    @RequestMapping("/vehicle/detail")
//    public ModelAndView details(HttpServletRequest request) {
//        ModelAndView modelAndView = new ModelAndView("pages/vehicle/detail");
//        modelAndView.addObject("id", request.getParameter("id"));
//        return modelAndView;
//    }
//    
//    
//    @RequestMapping("/vehicle/edit")
//	public ModelAndView edit(HttpServletRequest request) {
//		ModelAndView modelAndView = new ModelAndView("pages/vehicle/edit");
//		modelAndView.addObject("id", request.getParameter("id"));
//		return modelAndView;
//	}

	@RequestMapping(value ="/vehicle/aclslist" , method = RequestMethod.POST)
	  @ResponseBody
	  public Map<String, Object> list(HttpServletRequest request,String username,FaceAcls acls,PageInfo pageInfo) {
		Map<String, Object> res = new HashMap<>();
		System.out.println(username);
		  try {
	          Wrapper<FaceAcls> wrapper=new EntityWrapper<>();
	          wrapper.eq("username",username);
	          Page<FaceAcls> page = new Page<>(pageInfo.getPage(),pageInfo.getRows());
	          Page<FaceAcls> aclsList = aclsService.selectPage(page, wrapper);
	          res.put("rows", aclsList.getRecords());
	          res.put("total", aclsList.getTotal());
	          res.put("success", "true");
	          return res;
	      } catch (Exception e) {
	          res.put("success", "false");
	          return res;
	      }
	  }
  
  @RequestMapping("/vehicle/power")
  public String power(HttpServletRequest request,String username) {
	  request.setAttribute("username", username);
      return "pages/vehicle/power";
  }
    
    @RequestMapping(value = { "/rest/vehicle/list" }, method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> list(HttpServletRequest request, PageInfo pageInfo,FaceVehicle vehicle) {
        Map<String, Object> res = new HashMap<>();
        try {
            Wrapper<FaceVehicle> wrapper=new EntityWrapper<>();
            if(StringUtils.isNotBlank(vehicle.getVehicleNo())){
        		wrapper.eq("vehicle_no", vehicle.getVehicleNo());
            	}
            if(StringUtils.isNotBlank(vehicle.getCarType())){
       		wrapper.like("car_type", vehicle.getCarType());
            	}
            if(StringUtils.isNotBlank(vehicle.getDeviceNo())){
           		wrapper.like("device_no", vehicle.getDeviceNo());
               }
            Page<FaceVehicle> page = new Page<>(pageInfo.getPage(),pageInfo.getRows());
            Page<FaceVehicle> vehicleList = facevehicleService.selectPage(page, wrapper);
            
            res.put("rows", vehicleList.getRecords());
            res.put("total", vehicleList.getTotal());
            res.put("success", "true");
            return res;
        } catch (Exception e) {
            res.put("success", "false");
            return res;
        }
    }

    

    @RequestMapping("/rest/vehicle/info")
    public @ResponseBody
    BaseResult info(HttpServletRequest request) {
            Long id=Long.parseLong( request.getParameter("id"));
            FaceVehicle vehicle = facevehicleService.selectById(id);
            return BaseResult.success(vehicle);
    }
    
    @RequestMapping(value = { "/rest/vehicle/del" }, method = RequestMethod.POST)
    public @ResponseBody
    BaseResult del(HttpServletRequest request,String ids) {
        try {

        	if(StringUtils.isEmpty(ids)){
        		return BaseResult.success();
        	}
            List<String> asList = Arrays.asList(ids.split(","));
            facevehicleService.deleteBatchIds(asList);
            for (String id: asList) {
                this.syninfo(Long.valueOf(id),2);
            }
             return BaseResult.success();
        } catch (Exception e) {
        	log.error("发生异常了",e);
            return BaseResult.fail(e.getMessage());
        }
    }
    
   
    
    @RequestMapping(value = { "/rest/vehicle/save" }, method = RequestMethod.POST)
    public @ResponseBody
    BaseResult save(HttpServletRequest request,HttpServletResponse response,FaceVehicle faceVehicle) {
        
        try {
        	Date now = new Date();
        	faceVehicle.setCreateTime(now);
        	faceVehicle.setUpdateTime(now);
        	faceVehicle.setMqttUser(faceVehicle.getMqttUser());
			String mqttPasswd=App.encrypt(faceVehicle.getMqttPasswd());
        	faceVehicle.setMqttPasswd(mqttPasswd);
        	faceVehicle.setVehicleNo(faceVehicle.getVehicleNo());
        	faceVehicle.setCarType(faceVehicle.getCarType());
        	faceVehicle.setDeviceNo(faceVehicle.getDeviceNo());
            facevehicleService.insert(faceVehicle);
            this.syninfo(faceVehicle.getId(),1);
            FaceUsers users=new FaceUsers();
            users.setUsername(faceVehicle.getMqttUser());
            users.setPw(mqttPasswd);
            userService.insert(users);
            FaceAcls acls=new FaceAcls();
            acls.setUsername(faceVehicle.getMqttUser());
            aclsService.insert(acls);
        	return BaseResult.success();
        } catch (Exception e) {
        	log.error("发生异常了",e);
            return BaseResult.fail(e.getMessage());
        }
    }
    
    
    @RequestMapping(value = { "/rest/vehicle/update" }, method = RequestMethod.POST)
    public @ResponseBody
    BaseResult update(HttpServletRequest request, FaceVehicle vehicle,String meterNo) {
        Map<String, Object> res = new HashMap<>();
        try {
//        	vehicle.setMeterNo(meterNo);
            facevehicleService.updateById(vehicle);
        	this.syninfo(vehicle.getId(),3);
//        	MjMeter meter = new MjMeter();
//        	meter.setvehicleId(vehicle.getId());
//        	meter.setInstallTime(vehicle.getRegisteredTime());
//        	meter.setMeterId(meterId);
//			meterService.insert(meter );
            
        	return BaseResult.success();
        } catch (Exception e) {
        	log.error("发生异常了",e);
            return BaseResult.fail(e.getMessage());
        }
    }

    
	@RequestMapping(value ="vehicle/userList" , method = RequestMethod.POST)
	  @ResponseBody
	  public Map<String, Object> list(HttpServletRequest request,String username,FaceUsers users,PageInfo pageInfo) {
		Map<String, Object> res = new HashMap<>();
		System.out.println(username);
		  try {
	          Wrapper<FaceUsers> wrapper=new EntityWrapper<>();
	          wrapper.eq("username",username);
	          Page<FaceUsers> page = new Page<>(pageInfo.getPage(),pageInfo.getRows());
	          Page<FaceUsers> userList = usersService.selectPage(page, wrapper);
	          res.put("rows", userList.getRecords());
	          res.put("total", userList.getTotal());
	          res.put("success", "true");
	          return res;
	      } catch (Exception e) {
	          res.put("success", "false");
	          return res;
	      }
	  }
    private void syninfo(Long id,Integer opt) {
        FaceVehicle faceVehicle = this.facevehicleService.selectById(id);
        FaceSyncInfo faceSyncInfo = new FaceSyncInfo();
        faceSyncInfo.setTableName("face_vehicle");
        faceSyncInfo.setRecordId(id);
        faceSyncInfo.setOpt(opt);
        faceSyncInfo.setStatus(1);
        faceSyncInfo.setVehicleId(faceVehicle.getId());
        faceSyncInfo.setVehicleNo(faceVehicle.getVehicleNo());
        faceSyncInfo.setCreateTime(new Date());
        this.faceSyncInfoService.insert(faceSyncInfo);
    }
}


 